package com.hzit.order.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.hzit.common.utils.AlipayTemplate;
import com.hzit.common.utils.PayAsyncVo;
import com.hzit.common.utils.TbPayLog;
import com.hzit.order.dao.PayLogDao;
import com.hzit.order.entity.TbOrder;
import com.hzit.order.service.OrderService;
import com.hzit.order.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class PayServiceImpl implements PayService {
	@Autowired
	private AlipayTemplate alipayTemplate;
	@Autowired
	private PayLogDao payLogDao;
	@Autowired
	private OrderService orderService;
	//1. 生成支付页面
	@Override
	public String createPayPage(String outTradeNo, String totalFee,String subject) throws AlipayApiException {
		//获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(alipayTemplate.getGatewayUrl(),
				alipayTemplate.getApp_id(), alipayTemplate.getMerchant_private_key(),
				"json", alipayTemplate.getCharset(),
				alipayTemplate.getAlipay_public_key(), alipayTemplate.getSign_type());

		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(alipayTemplate.getReturn_url());     // 同步回调地址：处理完支付请求后要完成的后续操作
		alipayRequest.setNotifyUrl(alipayTemplate.getNotify_url());     // 异步回调地址：支付宝后台发给我们的信息，表示是否支付成功 scccess/fail (分布式事务：最大努力通知)

		//商户订单号，商户网站订单系统中唯一订单号，必填
		// String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//付款金额，必填
		// String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
		//订单名称，必填
		// String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
		//商品描述，可空
		// String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");

		// String subject = "hzit订单支付";

		String timeout = "1m";
		String body = "都是现在的紧俏商品！";
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","
				+ "\"total_amount\":\""+ totalFee +"\","
				+ "\"subject\":\""+ subject +"\","
				+ "\"body\":\""+ body +"\","
				+ "\"timeout_express\":\""+ timeout +"\","
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

		//若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
		//alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
		//		+ "\"total_amount\":\""+ total_amount +"\","
		//		+ "\"subject\":\""+ subject +"\","
		//		+ "\"body\":\""+ body +"\","
		//		+ "\"timeout_express\":\"10m\","
		//		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		//请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

		//请求
		String result = alipayClient.pageExecute(alipayRequest).getBody();

		//输出
		// out.println(result);
		return result;
	}

	//2. 异步回调方法
	@Override
	public String notifyCallBack(Map<String, String> params, PayAsyncVo vo) throws AlipayApiException {
		//2.1  进行验签处理
		boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
				alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名
		//2.2 如果验签通过，并且支付状态TRADE_STATUS=TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
		if(signVerified){
			if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
				//2.2.1 修改支付日志
				String outTradeNo = vo.getOut_trade_no();       // 得到订单编号
				//2.2.2 得到支付日志
				TbPayLog payLog = payLogDao.selectById(outTradeNo);
				//2.2.2 修改日志状态
				payLog.setTradeState("1");          // 1： 代表支付成功
				payLog.setPayTime(new Date());      // 2. 代表支付时间
				payLog.setTransactionId(vo.getTrade_no()); //3. 由支付宝后台返回的流水号
				payLogDao.updateById(payLog);       // 修改到数据库中


				//2.2.3 修改订单状态
				String orderListIds = payLog.getOrderList();
				String[] ids = orderListIds.split(",");
				for (String id : ids) {
					//2.2.4 得到订单
					TbOrder order = orderService.getById(id);
					//2.2.5 修改订单状态
					order.setStatus("2");       //2. 代表己支付
					//2.2.6 修改到数据库中
					orderService.updateById(order); //修改回数据库中
				}
				return "success";

			}
		}
		return "fail";
	}
}
